import Taro from "@tarojs/taro"
import ShareAppMessageObject = Taro.ShareAppMessageObject;
import ShareAppMessageReturn = Taro.ShareAppMessageReturn;

interface opt {
  title?:string;
  imageUrl?:string;
  redirect?:string;
}

type Option = (o:opt)=>void
function newOpt(...opts:Option[]):opt {
  let opt:opt = {};

  opts.forEach(f=> {
    f(opt);
  });

  return opt;
}

export function withShareAppMessageTitle(title:string):Option {
  return (o => {
    o.title = title
  })
}

export function withShareAppMessageImageUrl(imageUrl:string):Option {
  return (o => {
    o.imageUrl = imageUrl
  })
}

export function withShareAppMessageRedirect(redirect:string="/pages/redirect/redirect"):Option {
  return (o => {
    o.redirect = redirect
  })
}

export const redirectUrl = "redirectUrl";
export function onShareAppMessage(...opts:Option[]) {
  return function <T extends new (...args: any[]) => any>(constructor: T) {
    return class extends constructor {
      onShareAppMessage(_: ShareAppMessageObject):ShareAppMessageReturn {
        const opt = newOpt(...opts);
        const instance = Taro.getCurrentInstance();
        let params = "";
        for (let paramsKey in instance.router?.params) {
          params += `${paramsKey}=${encodeURIComponent(<string>instance.router?.params[paramsKey])}`
        }
        let path = instance.router?.path!;
        if (params.length) {
          path += `?${params}`
        }
        if (opt.redirect) {
          path = `${opt.redirect}?${redirectUrl}=${encodeURIComponent(redirectUrl)}`
        }

        console.log("path=", path);
        return {
          title: opt.title,
          path: path,
          imageUrl: opt.imageUrl
        };
      }
    };
  };
}
